import { Module } from 'vuex'
import { ILoginState } from './types'
import { IRootState } from '../types'
import router from '@/router'
import localCache from '@/utils/cache'
import { getUserInfoById, getUserMenusByRoleId } from '@/service/login/login'
import { IAccount } from '@/service/login/types'
import { ElMessage } from 'element-plus'
import { mapMenusRouter, mapMenusToPermissions } from '@/utils/mapMenusRouter'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      const routes = mapMenusRouter(userMenus)
      //动态添加menus路由
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      // 获取表格操作按钮的权限
      const permissions = mapMenusToPermissions(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    async postAccountLogin({ commit, dispatch }, pyload: IAccount) {
      let result: any = {}
      const response = await fetch('/api/login', {
        method: 'post',
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        },
        body: JSON.stringify(pyload)
      })
      if (response.status >= 200 && response.status < 300) {
        result = await response.json()
      } else {
        const message = await response.text()
        ElMessage({
          message,
          type: 'error',
          center: true
        })
        return
      }
      const { id, token } = result?.data
      commit('changeUserInfo', token)
      localCache.setCache('token', token)
      dispatch('getInitialDataAction', null, { root: true })
      //2.请求用户信息
      const userInfo = (await getUserInfoById(id)).data
      commit('changeUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)
      //3.请求用户菜单
      const userMenus = (await getUserMenusByRoleId(userInfo.role.id)).data
      for (const item of userMenus) {
        switch (item.id) {
          case 38:
            item.icon = 'Monitor'
            break
          case 1:
            item.icon = 'Setting'
            break
          case 9:
            item.icon = 'Goods'
            break
          case 41:
            item.icon = 'ChatLineRound'
            break
          default:
            break
        }
      }
      commit('changeUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)
      //4.跳转到首页
      router.push('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('changeToken', token)
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('changeUserMenus', userMenus)
      }
    }
  }
}
export default loginModule
